package com.example.springboot.utils;

import com.example.springboot.common.MinioConfig;
import com.example.springboot.exception.FileUploadException;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import java.util.UUID;

@Component
@AllArgsConstructor
@Slf4j
public class FileUtil {

    private final MinioConfig minioConfig;
    private final MinioClient minioClient;

    public void upload(MultipartFile file) {
//        String fileName = file.getOriginalFilename();
        // 生成唯一文件名防止冲突
//        String uniqueFileName = UUID.randomUUID().toString() + "_" + fileName;

        try {
            PutObjectArgs objectArgs = PutObjectArgs.builder()
                    .bucket(minioConfig.getBucketName())
                    .object(file.getOriginalFilename())
                    .stream(file.getInputStream(), file.getSize(), -1)
                    .contentType(file.getContentType())
                    .build();

            minioClient.putObject(objectArgs);

            log.info("文件上传成功: {}", file.getOriginalFilename() );

//            // 生成可以直接访问的URL
//            String url = String.format("%s/%s/%s",
//                minioConfig.getEndpoint(),
//                minioConfig.getBucketName(),
//                uniqueFileName);
//
//            log.info("获取url成功: {}", url);
//            return url;
        } catch (Exception e) {
            log.error("文件上传失败", e);
            throw new FileUploadException("上传文件失败: " + e.getMessage(), e);
        }
    }
}
